package com.example.linktop.sqlitedemo;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private MyOpenHelper  dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myInit();//初始化
    }


    private void myInit() {

        //初始化db
        dbHelper = new MyOpenHelper(getApplicationContext());
//        db = dbHelper.getReadableDatabase();//创建或打开一个db, 当存储空间不足返回只读db
//
//        if (db != null) {
//
//            System.out.println("db存在");
//
//        }



    }


    public void addBtn(View v) {

        try {
            SQLiteDatabase dbTmp = dbHelper.getWritableDatabase();
            dbTmp.execSQL("insert into info (name, phone) values (?,?)", new Object[]{"张三", "1238888888"});

            dbTmp.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void deleBtn(View v) {
        SQLiteDatabase dbTmp = dbHelper.getWritableDatabase();
        dbTmp.execSQL("delete from info where name = ?", new Object[]{"张三"});

        dbTmp.close();

    }

    public void updateBtn(View v) {
        SQLiteDatabase dbTmp = dbHelper.getWritableDatabase();
        dbTmp.execSQL("update info set phone = ? where name = ?", new Object[]{"13500000000","张三"});

        dbTmp.close();

    }

    public void selecBtn(View v) {

        SQLiteDatabase dbTmp = dbHelper.getReadableDatabase();
        Cursor cursor = dbTmp.rawQuery("select * from info", null);
        int rawIndx = 0;
        if (cursor != null && cursor.getCount() > 0) {

            Map[] mapArr = new Map[cursor.getCount()];

            while (cursor.moveToNext()) {
                //取出数据
                String name = cursor.getString(1);
                String phone = cursor.getString(2);

                //保存到map
                Map<String, String>  mapTmp =  new HashMap<>();
                mapTmp.put("name", name);
                mapTmp.put("phone", phone);
                mapArr[rawIndx++] =  mapTmp;

            }


            cursor.close();

            System.out.println("查询行数" + mapArr.length);


        }
    }


}
